<?php

namespace app\admin\controller\login;

use app\Base;
use app\service\admin\LoginServices;
use app\validate\admin\LoginValidate;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;
use think\response\Redirect;
use think\response\View;

/**
 * 账号密码
 * User : Du
 * Date : 2022/11/22
 * Time : 11:56
 * Class Login
 * @package projects\controller\admin\login
 */
class Login extends Base
{

    /**
     * 登录页面
     * User : Du
     * Date : 2022/11/22
     * Time : 11:57
     * @param LoginServices $service
     * @return Redirect|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function show(LoginServices $service)
    {
        if (is_array(session('manage_info'))) {
            return redirect('/manage/index');
        }
        $data = $service::webData();
        return view('login/index', ['data' => $data]);
    }

    /**
     * 账号验证
     * User : Du
     * Date : 2022/11/22
     * Time : 11:57
     * @param LoginServices $service
     * @param LoginValidate $validate
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function accountVerify(LoginServices $service, LoginValidate $validate): Json
    {
        //数据验证
        $res = $validate->check($this->params);
        if ($res !== true) {
            return $this->returnData('fail', $validate->getError());
        }
        $res = $service::checkUserLogin($this->params);
        if (is_string($res)) {
            return $this->returnData('fail', $res);
        }
        return $this->returnData();
    }

    /**
     * 退出登录
     * User : Du
     * Date : 2022/11/22
     * Time : 17:55
     * @param LoginServices $service
     * @return Redirect
     */
    public function signOut(LoginServices $service): Redirect
    {
        session(null);
        return redirect('/');
    }

    /**
     * 缓存client_id
     * @param LoginServices $services
     * @return Json
     * @throws Exception
     */
    public function updateCount(LoginServices $services): Json
    {
        $res = $services::updateCount($this->params);
        return $this->returnData();
    }

}